<template>
  <div class="foster-manage-container">
    <h1 class="page-title">🏠 宠物寄养管理</h1>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="宠物名称">
          <el-input v-model="searchForm.petName" placeholder="请输入宠物名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户姓名">
          <el-input v-model="searchForm.userName" placeholder="请输入用户姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="待确认" value="pending"></el-option>
            <el-option label="已确认" value="confirmed"></el-option>
            <el-option label="寄养中" value="fostering"></el-option>
            <el-option label="已完成" value="finished"></el-option>
            <el-option label="已取消" value="cancelled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 寄养列表 -->
    <el-card style="margin-top: 20px;">
      <el-table :data="fosterList" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="userName" label="用户姓名"></el-table-column>
        <el-table-column prop="phone" label="联系电话"></el-table-column>
        <el-table-column prop="petName" label="宠物名称"></el-table-column>
        <el-table-column prop="petBreed" label="品种"></el-table-column>
        <el-table-column prop="startDate" label="入住时间" width="120"></el-table-column>
        <el-table-column prop="endDate" label="离店时间" width="120"></el-table-column>
        <el-table-column prop="days" label="天数" width="80">
          <template slot-scope="scope">
            {{ scope.row.days }}天
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="费用">
          <template slot-scope="scope">
            <span class="price">¥{{ scope.row.totalPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.statusName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleView(scope.row)">
              详情
            </el-button>
            <el-button size="mini" type="success" @click="handleConfirm(scope.row)"
                       v-if="scope.row.status === 'pending'">
              确认
            </el-button>
            <el-button size="mini" type="warning" @click="handleFinish(scope.row)"
                       v-if="scope.row.status === 'fostering'">
              完成
            </el-button>
            <el-button size="mini" type="danger" @click="handleCancel(scope.row)"
                       v-if="['pending', 'confirmed'].includes(scope.row.status)">
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog title="寄养详情" :visible.sync="detailDialogVisible" width="600px">
      <el-descriptions :column="2" border v-if="currentFoster">
        <el-descriptions-item label="用户姓名">{{ currentFoster.userName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentFoster.phone }}</el-descriptions-item>
        <el-descriptions-item label="宠物名称">{{ currentFoster.petName }}</el-descriptions-item>
        <el-descriptions-item label="宠物品种">{{ currentFoster.petBreed }}</el-descriptions-item>
        <el-descriptions-item label="入住时间">{{ currentFoster.startDate }}</el-descriptions-item>
        <el-descriptions-item label="预计离店">{{ currentFoster.endDate }}</el-descriptions-item>
        <el-descriptions-item label="寄养天数">{{ currentFoster.days }}天</el-descriptions-item>
        <el-descriptions-item label="每日费用">¥{{ currentFoster.pricePerDay }}/天</el-descriptions-item>
        <el-descriptions-item label="总费用">
          <span class="price">¥{{ currentFoster.totalPrice }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentFoster.status)">{{ currentFoster.statusName }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentFoster.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import fosterApi from '@/api/foster'

export default {
  name: 'FosterManage',
  data () {
    return {
      searchForm: {
        petName: '',
        userName: '',
        status: ''
      },
      fosterList: [],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      detailDialogVisible: false,
      currentFoster: null
    }
  },
  created () {
    this.loadFosterList()
  },
  methods: {
    async loadFosterList () {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ...this.searchForm
        }
        const res = await fosterApi.getFosterRecords(params)
        this.fosterList = res.data || []
        this.pagination.total = res.total || 0
      } catch (error) {
        this.$message.error('加载失败：' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },
    handleSearch () {
      this.pagination.currentPage = 1
      this.loadFosterList()
    },
    handleReset () {
      this.searchForm = { petName: '', userName: '', status: '' }
      this.pagination.currentPage = 1
      this.loadFosterList()
    },
    async handleView (row) {
      try {
        const res = await fosterApi.getFosterDetail(row.id)
        this.currentFoster = res.data || row
        this.detailDialogVisible = true
      } catch (error) {
        this.currentFoster = row
        this.detailDialogVisible = true
      }
    },
    handleConfirm (row) {
      this.$confirm('确认该寄养申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await fosterApi.updateFosterStatus(row.id, 'confirmed')
          this.$message.success('已确认')
          this.loadFosterList()
        } catch (error) {
          this.$message.error('确认失败：' + (error.message || '未知错误'))
        }
      })
    },
    handleFinish (row) {
      this.$confirm('确认寄养已完成吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await fosterApi.updateFosterStatus(row.id, 'finished')
          this.$message.success('已完成')
          this.loadFosterList()
        } catch (error) {
          this.$message.error('操作失败：' + (error.message || '未知错误'))
        }
      })
    },
    handleCancel (row) {
      this.$confirm('确认取消该寄养预约吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await fosterApi.cancelFosterReserve(row.id)
          this.$message.success('已取消')
          this.loadFosterList()
        } catch (error) {
          this.$message.error('取消失败：' + (error.message || '未知错误'))
        }
      })
    },
    getStatusType (status) {
      const typeMap = {
        'pending': 'warning',
        'confirmed': 'primary',
        'fostering': 'success',
        'finished': 'info',
        'cancelled': 'danger'
      }
      return typeMap[status] || 'info'
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.loadFosterList()
    },
    handleCurrentChange (val) {
      this.pagination.currentPage = val
      this.loadFosterList()
    }
  }
}
</script>

<style scoped>
.foster-manage-container {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  color: #333;
}

.search-card {
  margin-bottom: 20px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}
</style>
